package com.cnpinxi.controller.admin.product;

import com.cnpinxi.controller.base.BaseController;
import com.cnpinxi.def.Constant;
import com.cnpinxi.domain.AdminUser;
import com.cnpinxi.domain.ProductEntity;
import com.cnpinxi.domain.ProductSerial;
import com.cnpinxi.myRunTime.MyRunTimeExcption;
import com.cnpinxi.result.ResultObj;
import com.cnpinxi.service.AdminSerialService;
import com.cnpinxi.service.ProductEntityService;
import com.cnpinxi.util.BarcodeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@RequestMapping("/admin/productEntity")
@Controller
public class AdminProductEntityController extends BaseController {

    @Autowired
    ProductEntityService productEntityService;
    @Autowired
    AdminSerialService adminSerialService;

    /**
     * 拉取所有产品实体（没有使用查询图片方法）
     *
     * @param request
     * @return
     */
    @RequestMapping("/getProductEntityList")
    public ModelAndView getProductEntityList(HttpServletRequest request, Integer page, Integer pageSize) {
        ModelAndView m = new ModelAndView("/admin/product/getProductEntityList");
        Map<String, String> map = this.showRequestParameters(request);
        if (page == null || page == 0) {
            page = Constant.PAGENUM;
        }
        // 设置每页记录数
        if (pageSize == null || pageSize == 0) {
            pageSize = Constant.PAGESIZENum;
        }
        map.put("page", String.valueOf(page));
        map.put("pageSize", String.valueOf(pageSize));
        PageHelper.startPage(page, pageSize);
        List<ProductEntity> productEntityList = productEntityService.getProductEntityList(map);
        PageInfo<ProductEntity> pageinfo = new PageInfo<>(productEntityList);
        m.addObject("pageinfo", pageinfo);
        m.addObject("bean", map);
        return m;
    }

    /**
     * 跳转到添加或修改页面
     *
     * @param request
     * @return
     */
    @RequestMapping("/getProductEntity")
    public ModelAndView getProductEntity(HttpServletRequest request) {
        ModelAndView m = new ModelAndView("/admin/product/getProductEntity");
        Map<String, String> map = this.showRequestParameters(request);
        String productEntityId = map.get("productEntityId");
        String productId = map.get("productId");
        ProductEntity productEntity = new ProductEntity();
        if (productEntityId != null) {
            productEntity = productEntityService.getProductEntityById(Long.parseLong(productEntityId));
            productId=String.valueOf(productEntity.getProductId());
        }
        m.addObject("productEntity", productEntity);
        m.addObject("productId", productId);
        return m;
    }

    /**
     * 添加或修改产品实体
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/modifiyProductEntity")
    @ResponseBody
    public String modifiyProductEntity(HttpServletRequest request, ProductEntity productEntity) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        logger.info(productEntity.toString());
        try {
            productEntity=   productEntityService.modifyProductEntity(productEntity);
            resultObj.setMsg("操作成功！");
        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg("操作失败！");
            e.printStackTrace();
        }
        return resultObj.toJson();
    }

    /**
     * 生成产品序列号
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/makeProductEntitySerial")
    @ResponseBody
    public String makeProductEntitySerial(HttpServletRequest request) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_FAIL);
        AdminUser user=(AdminUser)request.getSession().getAttribute(Constant.SESSION_KEY_ADMDIN_USER_LOGIN);
        Map<String, String> map = this.showRequestParameters(request);
        map.put("adminUserId",String.valueOf(user.getTid()));
        //List<ProductSerial> productSerialList = adminSerialService.selectProductSerial(map);
        //logger.info(productEntity.toString());
        try {
            /*if(productSerialList.size() >0){
                throw new MyRunTimeExcption("请勿重复生成序列号！");
            }*/
            int num = adminSerialService.insertProductSerial(map);
            if(num==1){
                resultObj.setCode(ResultObj.CODE_SUCCESS);
                resultObj.setMsg("操作成功！");
            }
        }catch (MyRunTimeExcption e) {
            resultObj.setMsg(e.getMessage());
        }catch (Exception e) {
            resultObj.setMsg("操作失败！");
            e.printStackTrace();
        }
        return resultObj.toJson();
    }
    /**
     *得到产品序列号列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/getSerialList")
    public ModelAndView getSerialList(HttpServletRequest request, Integer page, Integer pageSize) {
        ModelAndView m = new ModelAndView("/admin/product/getSerialList");
        Map<String, String> map = this.showRequestParameters(request);
        if (page == null || page == 0) {
            page = Constant.PAGENUM;
        }
        // 设置每页记录数
        if (pageSize == null || pageSize == 0) {
            pageSize = Constant.PAGESIZENum;
        }
        map.put("page", String.valueOf(page));
        map.put("pageSize", String.valueOf(pageSize));
        PageHelper.startPage(page, pageSize);
        List<ProductSerial> productSerialList = adminSerialService.selectProductSerial(map);
        PageInfo<ProductSerial> pageinfo = new PageInfo<>(productSerialList);
        m.addObject("pageinfo", pageinfo);
        m.addObject("bean", map);
        return m;
    }

    /**
     * 根据内容生成条形码
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getBarcode")
    public ModelAndView getBarcode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ModelAndView m = new ModelAndView("/admin/product/serialBarcode");
        Map<String, String> map = this.showRequestParameters(request);
        List<ProductSerial> productSerialList = adminSerialService.selectProductSerial(map);
        List<String> codeUrlList = new ArrayList<>();
        String codeUrl = "";
        String path= "";
        ProductSerial ps = null;
        logger.warn("【进入生成条形码的控制层。。。。。。】");
        try {
           /* if(productSerialList.size() ==0){
                throw new MyRunTimeExcption("请生成序列号！");
            }*/
           for (ProductSerial productSerial:productSerialList) {
                codeUrl = productSerial.getSerialNumber();
                path = request.getSession().getServletContext().getRealPath("/")+"/pic/"+codeUrl+".png";
                BarcodeUtil.generateFile(codeUrl,path);
                codeUrlList.add(codeUrl);
                //更改序列号状态
                ps = new ProductSerial();
                ps.setStauts(Byte.parseByte("1"));
                ps.setProductEntityId(Long.parseLong(map.get("productEntityId")));
                ps.setSerialNumber(codeUrl);
                adminSerialService.updateSerialStatus(ps);
            }
           // BarcodeUtil.generate(codeUrl, response.getOutputStream());
        }  catch (MyRunTimeExcption e) {
            logger.warn("【" + e.getMessage() + "】。。。。。。");
            //response.getWriter().write(e.getMessage());
        }catch (Exception e) {
            logger.warn("【生成条形码失败。。。。。。】");
            logger.warn("【" + e.getMessage() + "】。。。。。。");
        }
        m.addObject("codeUrlList", codeUrlList);
        m.addObject("bean", map);
        return m;
    }


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }
}
